import React, { useCallback, useEffect, useState } from 'react';
import { Button, message } from 'antd';
import AddOrEdit from './components/AddOrEdit';
import TableBox from './components/TableBox';
import columns from './components/TableBox/columns';
import {
  fetchCategoryList,
  fetchAddCategory,
  fetchUploadCategory,
} from '@/services/category';
import styles from './index.less';

const Category = () => {
  const [tableData, setTableData] = useState<any[]>([]);
  const [visible, setVisible] = useState<boolean>(false);
  const [flag, setFlag] = useState<string>('');
  const [rowRecord, setRowRecord] = useState<any>({});

  useEffect(() => {
    fetchCategoryList().then((res) => {
      setTableData(res);
    });
  }, []);

  const handleAdd = useCallback(() => {
    setFlag('add');
    setVisible(true);
  }, []);

  const handleCancel = useCallback(() => {
    setVisible(false);
  }, []);

  const handleEdit = useCallback((value) => {
    setRowRecord(value);
    setFlag('edit');
    setVisible(true);
  }, []);

  const handleSubmit = useCallback(
    async (value) => {
      if (flag === 'add') {
        const res = await fetchAddCategory(value);
        if (!res) {
          message.success('添加成功');
          fetchCategoryList().then((res) => {
            setTableData(res);
          });
          setVisible(false);
          setFlag('');
        }
      } else if (flag === 'edit') {
        console.log(value);
        const res = await fetchUploadCategory(rowRecord.id, value);
        if (!res) {
          message.success('编辑成功');
          fetchCategoryList().then((res) => {
            setTableData(res);
          });
          setVisible(false);
          setFlag('');
        }
      }
    },
    [flag],
  );

  const getColumns = useCallback(
    () => columns({ handleEdit }),
    [handleEdit, columns],
  );

  return (
    <div className={styles.container}>
      <Button type="primary" className={styles.addbtn} onClick={handleAdd}>
        添加分类
      </Button>
      <TableBox columns={getColumns()} dataSource={tableData} />
      <AddOrEdit
        visible={visible}
        onCancelWrite={handleCancel}
        flag={flag}
        onSubmit={handleSubmit}
        selectData={tableData}
        rowRecord={rowRecord}
      />
    </div>
  );
};

export default Category;
